<template>
    <div style="" class="formBox">
        <div class="bpm-result" v-if="!taskStatus">
            <img src="@public/image/formCustom/bpmOk.png">
            <span class="bpm-result-name">{{i18n("successSubmit","流程审批成功提交")}}</span>
            <a-button type="primary" style="width: 240px;" @click="bpmRefresh">{{i18n("seeFlowDetail","查看流程明细")}}</a-button>
            <a class="bpm-result-a">{{i18n("countDown","倒计时")}} {{countdown}}s {{i18n("jumpPage","后跳转到结果页")}}</a>
        </div>
        <bpm-header :title="bpmInst.subject" :version="bpmInst.version" :user="bpmInst.createBy" v-if="taskStatus"></bpm-header>
        <div class="bpm-task-content" v-if="taskStatus">
            <a-tabs class="rx-a-tabs" default-active-key="details" @change="changeTabs($event)">
                <template #rightExtra>
                  <div class="tabs-toolbar">
                    <task-tool-bar ref="taskToolBar" :bpmTaskDetail="bpmTaskDetail" :cur-data="curData" :taskConfig="taskConfig" @showBpmCommu="showBpmCommu" :bpmActionType="'bpmTaskStart'"/>
                  </div>
                </template>
                <a-tab-pane key="details" :tab="i18n('list.detail', '详情')">
                    <div class="tab-center-bg">
                        <div class="tab-center-content" ref="tabCenter" :class="{'tab-center-content-show':showHistory}">
                            <div class="tab-center">
                                <!--单据实例信息-->
                                <bpm-inst-info v-if="bpmInst" :bpmInst="bpmInst"/>

                                <!--显示提交的沟通-->
                                <task-commu :task-linkup-param.sync="taskLinkupParam"
                                            @commuTaskRevoked="reloadTaskInfo()"/>
                                <!--表单-->
                                <rx-forms ref="rxForms" v-if="processConfig.formType=='online'"></rx-forms>
                                <component v-else-if="processConfig.formType=='custom'"
                                           ref="customForm" :is="formComponent"
                                           :params="urlParamData"
                                           :pk="pk"></component>
                                <url-view v-if="processConfig.formType=='outsideUrl'" ref="outSideUrlForm"   :pk="pk"
                                          :showUrl="outSideUrl" :urlParamData="urlParamData"></url-view>
                                <!--任务沟通-->
                                <bpm-commu-history
                                    :inst-id="instId"
                                    :bpm-task="bpmTask"
                                    :bpmTaskDetail="bpmTaskDetail"
                                    v-model:bpmCommuShow="bpmCommuShow"
                                    @doReplyCommu="doReplyCommu"/>
                                <!--留言-->
                                <bpm-inst-msgs :instId="instId" v-model:msgShow="msgShow"/>
                                <bpm-inst-logs :instId="instId" v-model:logShow="logShow"/>

                            </div>
                        </div>
                        <div class="bpm-history-button" @click="foldRight">
                            <rx-icon-show icon="iconVue3jpaas-icon_shenpilishi"></rx-icon-show>
                        </div>
                        <div class="bpm-task-history" :class="{'bpm-task-show':showHistory}">
                            <!--审批历史-->
                            <div class="history-roll-box" :class="{'history-roll':historyRoll}">
                                <div class="bpm-task-history-text">
                                    <span>{{i18n('list.appHistory', '审批历史')}}</span>
                                    <span class="bpm-history-close" @click="foldRight">
                                        <CloseOutlined />
                                    </span>
                                </div>
                                <bpm-history
                                    ref="bpmHistory"
                                    :inst-id="instId"
                                    :bpm-task="bpmTask"
                                    v-model:historyShow="historyShow"/>
                            </div>
                        </div>
                    </div>
                </a-tab-pane>
                <a-tab-pane key="flowChart" :tab="i18n('list.flowChart', '流程图')">
                    <bpm-image-view v-if="isShowImage" :task-id="taskId" :preview="false" :formData="formData"></bpm-image-view>
                </a-tab-pane>
            </a-tabs>
            <ai-agent v-if="enableAi" :promptList="[]" :welcomeDescription="'有什么问题都可以向我提问~'" @fetchSuggestedQuestions="fetchSuggestedQuestions" @openParamsChange="openParamsChange" :incomingInfo="incomingInfo" :chatMessage="chatMessage" :questions="questions" />
        </div>

    </div>

</template>
<script>
import {RxDialog, Util, RxFit,RxError,TokenUtil,AiAgent} from '@lowcode/jpaas-base-lib';
// import {RxDialog, Util, RxFit, RxTextBoxList,RxError} from '@lowcode/jpaas-base-lib';
import {RxUserInfo,BpmImageView} from '@lowcode/jpaas-share-component';
import BpmtaskApi from "@/common/api/bpm/bpmTask";
import BpmInstMsgs from "../components/BpmInstMsgs.vue"
import BpmInstLogs from "../components/BpmInstLogs.vue";
import TaskToolBar from "./TaskToolBar.vue";
import bpmHistory from "../components/bpmHistory.vue";

import RxForms from "./RxForms.vue";
import BpmInstInfo from "../components/BpmInstInfo.vue";
import BpmCommuHistory from "../components/BpmCommuHistory.vue";
import TaskCommu from "../components/TaskCommu.vue";
import TaskCommuReply from "../components/TaskCommuReply.vue";
import bpmHeader from "./bpmHeader.vue";
import FlowUtil from "../js/FlowUtil.js";
import { mapState } from 'pinia';
import userUser from "@/stores/userUser";
import UrlView from "@/views/modules/form/FormCustomView/components/ColumnView/UrlView.vue";
import UrlParamsUtil from "@/views/modules/bpm/OpenDoc/js/url-params-util";
import AppUtil   from "@/assets/js/AppUtil";

export default {
    name: "BpmTaskStart",
    mixins: [FlowUtil,UrlParamsUtil],
    components: {
        AiAgent,
        RxError,
        bpmHistory,
        TaskCommuReply,
        TaskCommu,
        BpmCommuHistory,
        BpmInstInfo,
        RxDialog,
        TaskToolBar,
        BpmInstMsgs,
        BpmInstLogs,
        RxFit,
        // RxTextBoxList,
        RxForms,
        RxUserInfo,
        bpmHeader,
        BpmImageView,
        UrlView
    },
    props: {
        taskId: {
            type: String,
            required: true
        },
        instId: {
            type: String,
            required: true
        },
        layerid: String,
        destroy: Function
    },
    computed:{
        ...mapState(userUser, ['user']),
        showStatus() {
            if (!this.processConfig.switchOptions) {
                return true;
            }
            let rtn = this.processConfig.switchOptions.includes("showStatus");
            return rtn;

        }
    },
    data() {
        return {
            questions:[],
            incomingInfo:"",
            chatMessage:{
              url: "/api/api-bpm/bpm/core/bpmAi/calBpmAiApprove",
              body: {
                response_mode: "streaming"
              }
            },
            enableAi:false,
            curData:[],
            collapsed:false,
            title: this.i18n('list.taskDetail','任务详情'),
            msgTypes: '',
            checkType: 'AGREE',
            historyShow: false,
            bpmCommuShow:false,
            msgShow: false,
            bpmInst: {instId: ''},
            bpmTask: {taskId: this.taskId},
            isCanBack: false,
            canCheck: true,
            canRecorveLinkup: false,
            bpmCmTaskInfos: [],
            isAllowLinkup: true,
            backPathResult: {},
            nodeExecutors: [],
            processConfig: {
                formType: "online"
            },
            taskConfig: {},
            bpmTaskDetail: {},
            msgSubmitting: false,
            logShow: false,
            //任务沟通参数
            taskLinkupParam: {
                canStartLinkup: false,
                canRevokeLinkup: false,
                canReplyLinkup: false,
                bpmCmTaskInfos: []
            },
            //回复沟通任务
            taskLinkupReply: {
                msgTypes: '',
                opinion: '',
                lpReplyVisible: false,
            },
            formComponent: "",

            outSideUrl:"",
            urlParamData:[],

            pk: "",
            taskStatus: true,
            errorMessage: "",
            //根实例
            rootVm: true,
            status: '',
            showHistory:false,
            formData:{},
            isShowImage:false,
            historyRoll:true,
            countdown:5,
            //幂等号
            idempotenceid:""
        }
    },
    created() {
        this.loadTaskInfo();
        let showTaskHistory=Util.getKey("showTaskHistory");
        if(showTaskHistory){
            this.showHistory=showTaskHistory=="YES";
        }
        this.updateReceiversReaded();
    },
    methods: {
        async fetchSuggestedQuestions(messageId) {
          try {
            let token = TokenUtil.getToken();
            // 调用建议问题接口，示例需要根据实际API调整
            const response = await fetch("/api/api-bpm/bpm/core/bpmAi/suggested/"+messageId, {
              method: 'GET',
              headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
              }
            });

            const data = await response.json();
            this.questions = data || [];
          } catch (error) {
            console.error('获取建议问题失败:', error);
          }
        },
        openParamsChange(){
          let token = TokenUtil.getToken();
          this.chatMessage.header = {
            Authorization: `Bearer ${token}`,
            appId: this.$route.query.appId
          };
          this.chatMessage.body.formData = this.$refs.rxForms.getData();
          this.incomingInfo = this.bpmTaskDetail.prompt;
        },
        /**
         * 如果是沟通任务，更新为已阅
         */
        updateReceiversReaded(){
            BpmtaskApi.updateReceiversReaded(this.taskId,2);
        },
        foldRight(){
            this.showHistory = !this.showHistory;
            let showTaskHistory=this.showHistory?'YES':'NO';
            Util.setKeyVal("showTaskHistory",showTaskHistory);
        },
        changeTabs(key){
            if(key=='flowChart'){
                this.getFormData();
            }else {
                this.isShowImage=false;
            }
        },
        getFormData(){
            let formType = this.processConfig.formType;
            let rxForms = this.$refs.rxForms;
            if (formType == "online" && rxForms) {
              this.formData = rxForms.getData();
            }
            this.isShowImage=true;
        },
        i18n(name,text,key){
            return this.$ti18(name,text,"bpmInst",key);
        },
        showBpmCommu(val){
            this.bpmCommuShow=true;
        },
        doReplyCommu(val){
            this.bpmCommuShow=false;
            this.$refs.taskToolBar.doReplyCommu();
        },
        //刷新任务
        async loadTaskInfo() {
            let self = this;
            if (!this.taskId) {
                this.taskId = this.$route.params.taskId;
            }
            if (!this.instId) {
                this.instId = this.$route.params.instId;
            }
            let res = await BpmtaskApi.getAllDetail(this.taskId);
            if (!res.success) {
                this.taskStatus = false;
                this.errorMessage = res.message;
                this.bpmCountdown()
                return;
            }
            //获取幂等号
            this.idempotenceid=res.headers.idempotenceid;
            this.status = res.data.bpmInst.status;
            this.bpmTaskDetail = res.data;
            this.enableAi = this.bpmTaskDetail.enableAi;

            if (res.data.bpmTask == null) {
                if (self.destroy) {
                    this.$notification.open({
                        message: self.$ti18('rxMsa.actionTips','操作提示'),
                        description:
                            self.i18n('completed','当前任务已经完成或删除，请刷新数据界面再操作！'),
                    });
                    Util.closeWindow(self, "ok", {});
                    return;
                } else {
                    alert(self.i18n('completed','当前任务已经完成或删除，请刷新数据界面再操作！'));
                    window.close();
                }
            }else {
                //当前实例为锁定 任务不是锁定 则显示为运行中
                if(this.status =='LOCKED' && res.data.bpmTask.status!='LOCKED'){
                    this.status ='RUNNING';
                }
                else if(this.status =='RUNNING' && res.data.bpmTask.status=='LOCKED'){
                    //当前实例为运行中 任务是锁定 则显示为锁定
                    this.status ='LOCKED';
                }
            }

            Object.assign(self, res.data);
            var curUser = this.user;
            let taskConfig = res.data.taskConfig;
            var contextData = {
                type: "usetask",
                curUserId: curUser.userId,
                curUserName: curUser.fullName,
                account: curUser.account,
                deptId: curUser.deptId,
                nodeId: self.bpmTask.key,
                nodeName: self.bpmTask.name,
                instId: self.instId,
                defId: self.bpmInst.defId,
                instNo: self.bpmInst.billNo,
                taskId: self.taskId,
                tenantId: curUser.tenantId,
                tenantLabel: curUser.tenantLabel,
                opinionHistorys: res.data.bpmCheckHistories,
                alias: taskConfig.alias,
                subject:self.bpmInst.subject,
                //当前是否为发起人
                starter:self.bpmInst.createBy==curUser.userId,
            };
            this.handFormConfig(res.data.processConfig, taskConfig, res.data.bpmInst);

            if (this.processConfig.formType == 'online') {
                this.$nextTick(function () {
                    self.$refs.rxForms.setData(res.data.formData.data, false, contextData);
                    self.curData = res.data.formData.data ;
                })
            }
            else{
                //设置外部URL表单的主键
                this.pk= res.data.bpmInst.busKey;
                this.curData={pk:this.pk};
            }
        },
        bpmCountdown(){
            setInterval(() => {
                if (this.countdown > 0) {
                    this.countdown--;
                } else {
                    this.bpmRefresh()
                }
            }, 1000);
        },
        bpmRefresh(){
            let appId = this.$route.query.appId;
            let href =appId? window.location.pathname+'?appId='+appId:window.location.pathname;
            window.location.href = href
        },
        //处理表单配置。
        handFormConfig(conf, taskConfig, bpmInst) {
            var config = Util.deepClone(this.processConfig);
            this.processConfig = Object.assign(config, conf);
            if (!this.processConfig.formType) {
                this.processConfig.formType = "online"
            }
            //startForm
            let taskForm=taskConfig.form.formpc;
            if (taskForm && taskForm.length > 0) {
                var form = taskForm[0];
                this.handForm(form,bpmInst);
                return;
            }
            //获取全局。
            let globalForm=this.processConfig.globalForm.formpc;
            if (globalForm && globalForm.length > 0) {
                var form = globalForm[0];
                this.handForm(form,bpmInst);
            }
        },
        handForm(form,bpmInst){
            if (form && form.type == "custom") {
                this.pk = bpmInst.busKey;
                this.processConfig.formType = "custom";
                this.formComponent = AppUtil.loadComponent(form.component);
                this.handFormParams(form.id);
            }
            if(form && form.type=="outsideUrl"){
                this.pk = bpmInst.busKey;
                this.outSideUrl=form.component;
                this.processConfig.formType="outsideUrl";
                this.handFormParams(form.id);
            }
        },
        /**
         * 处理自定义表单参数.
         * @param formId
         */
        handFormParams(formId){
            var contextData={
                defId:this.bpmInst.defId,
                instId:this.instId,
                taskId:this.taskId,
                nodeId:this.bpmTask.key,
                nodeName:this.bpmTask.name,
                stageType: "usetask",
            }
            this.handUrlParams(formId,contextData);
        }


    }
}
</script>
<style scoped>
.rx-a-tabs ::v-deep(.ant-tabs-extra-content){
    padding-right: 10px;
}
.rx-a-tabs ::v-deep(.ant-tabs-nav){
    margin-bottom: 0;
}
.rx-a-tabs ::v-deep(.ant-tabs-nav-wrap){
    padding-left: 10px;
}
.tab-center-bg{
    width: 100%;
    height: 100%;
    background: #F5F5F5;
    overflow: auto;
    position: relative;
}
.tabs-toolbar{
    height: 45px;
    display: flex;
    align-items: center;
}
.tab-center-content{
    display: inline-block;
    vertical-align: top;
    width: 100%;
    min-height: 100%;
    background: #F5F5F5;
    transition: all .5s;
    padding-top: 10px;
}
.tab-center-content-show{
    width: calc( 100% - 340px );
}

.tab-center{
    box-sizing: border-box;
    max-width: 1300px;
    width: 80%;
    margin:0 auto 10px;
    min-height: calc( 100vh - 120px );
    background: #fff;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
}
.bpm-task-history{
    vertical-align: top;
    display: inline-block;
    background-color: #fff;
    width: 0;
    opacity: 0;
    transition: all .5s;
    min-height: 100%;
    position: relative;
    z-index: 11;
    overflow: hidden;
}
.bpm-history-button{
    top: 10px;
    right: 10px;
    position: absolute;
    width: 44px;
    height: 44px;
    background: #fff;
    box-shadow: 0 3px 10px 1px rgba(0,0,0,0.06);
    border-radius: 4px;
    z-index: 9;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}
.bpm-task-history-text{
    padding: 10px ;
    border-bottom: 1px solid #E8E8E8;
    font-size: 16px;
    color: #333;
    font-weight: bold;
    display: flex;
    justify-content: space-between;
}
.bpm-history-close{
    display: inline-block;
    padding:0 4px;
    cursor: pointer;
}
.bpm-history-close:hover{
    color: #4d9eff;
}
.bpm-task-show{
    width:340px ;
    opacity: 1;
}

.rx-a-tabs >>> .ant-tabs-bar.ant-tabs-top-bar{
    margin-bottom: 0!important;
}
.bpm-task-content{
    height: calc( 100% - 50px);
}
.rx-a-tabs{
    width: 100%;
    height: 100%;
}
.formBox {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
}
.history-roll-box{
    width: 340px;height: 100%;
}
.history-roll-box.history-roll{
    height: auto;
}
.history-roll ::v-deep(.drawer-body){
    min-height:calc( 100% - 45px )!important;
    height: auto!important;
}
.history-roll ::v-deep(.drawer-body-roll){
    position: initial!important;
}
.bpm-result{
    display: flex;
    padding-top: 180px;
    flex-direction: column;
    align-items: center;
}
.bpm-result img{
    width: 184px;
}
.bpm-result-name{
    font-size: 24px;
    line-height: 90px;
    color: #303030;
}
.bpm-result-a{
    font-size: 16px;
    line-height: 40px;
    color: #4285f4;
}
</style>
